package com.anjun.springandjdbc.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.anjun.springandjdbc.dao.Person;
import com.anjun.springandjdbc.dao.PersonMapper;
import com.anjun.springandjdbc.service.PersonService;

public class PersonServiceImpl implements PersonService{
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public int insert(Person person) {
		return jdbcTemplate.update("insert into person(name) values(?)",new Object[]{person.getName()},
				new int[]{java.sql.Types.VARCHAR});
	}

	public int update(Person person) {
		return jdbcTemplate.update("update person set name = ? where id = ?",new Object[]{person.getName(),person.getId()},
				new int[]{java.sql.Types.VARCHAR,java.sql.Types.INTEGER});
	}

	public int delete(Person person) {
		jdbcTemplate.update("delete from person where id = 9");
		jdbcTemplate.update("delete from person where idfddsfsddfdfs = ?");
		return jdbcTemplate.update("delete from person where id = ?",new Object[]{person.getId()},
				new int[]{java.sql.Types.INTEGER});
	}

	public Person findOne(Integer id) {
		return jdbcTemplate.queryForObject("select * from person where id = ? ", new Object[]{id}, new PersonMapper());
	}

	public List<Person> findAll() {
		return jdbcTemplate.query("select * from person", new PersonMapper());
	}
	
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("jdbc.xml");
		PersonService personService = (PersonService) ctx.getBean("personService");
////		personService.insert(new Person("anjun"));
////		System.out.println(personService.findOne(1).getId() + "," + personService.findOne(1).getName());
		Person person = new Person("tom");
		person.setId(1);
//		personService.update(person);
//		System.out.println(personService.findOne(1).getId() + "," + personService.findOne(1).getName());
//		List<Person> list = personService.findAll();
//		for (Person person : list) {
//			System.out.println(person.getId() + "," + person.getName());
//		}
		personService.delete(person);
	}

}
